import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import GatherParameter from '@main/entities/service/admin/gather/gather-parameter.entity';
import { ApiException } from '@main/common/exceptions/api.exception';
import GatherMachineParameter from '@main/entities/service/admin/gather/gather-machine-parameter.entity';
import { SysOperationLogService } from '../../system/operationLog/operationLog.service';

@Injectable()
export class GatherParameterService {
  constructor(
    @InjectRepository(GatherParameter)
    private gatherParameterRepository: Repository<GatherParameter>,
    @InjectRepository(GatherMachineParameter)
    private gatherMachineParameterRepository: Repository<GatherMachineParameter>,
    private operationLogService: SysOperationLogService,
  ) {
    this.initGatherParameter();
  }

  async initGatherParameter() {
    const paramConfigList = await this.gatherParameterRepository.find();

    if (paramConfigList.length === 0) {
      console.log('初始化参数');

      this.gatherParameterRepository.insert([
        {
          parameterName: '设备状态',
          parameterCode: 'equipmentStatusGet',
        },
        {
          parameterName: '生产车速',
          parameterCode: 'productionSpeedGet',
        },
        {
          parameterName: '送纸状态',
          parameterCode: 'paperFeedingStatusGet',
        },
        {
          parameterName: '产量设定',
          parameterCode: 'productionQuantitySet',
        },
        {
          parameterName: '实时产量',
          parameterCode: 'productionQuantityGet',
        },
      ]);
    }
  }

  async list() {
    return await this.gatherParameterRepository.find();
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { parameterName, parameterCode } = entity;

    return await this.gatherParameterRepository.findAndCount({
      where: {
        parameterName: Like(`%${parameterName}%`),
        parameterCode: Like(`%${parameterCode}%`),
      },
      order: {
        updateTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });
  }

  /**
   * 新增
   */
  async add(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const gatherParameter = await this.gatherParameterRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
    databaseOperationLogList.push({
      type: 'add',
      dataType: 'obj',
      database: 'GatherParameter',
      checkOnlyKeyList: [],
      data: gatherParameter,
      whereObj: null,
      remark: `GatherParameter表新增数据`,
    });
    await this.operationLogService.add(
      {
        type: 'add',
        msg: `采集管理模块新增数据`,
        databaseOperationLogList,
        remark: `新增采集${data.parameterName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 更新
   */
  async update(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];

    const { id, parameterName, remark } = data;

    await this.gatherParameterRepository.update(
      { id },
      { parameterName, remark, updateName: user.nickName, updateUserName: user.userName }
    );

    databaseOperationLogList.push({
      type: 'update',
      dataType: 'obj',
      database: 'GatherParameter',
      checkOnlyKeyList: [],
      data: { parameterName, remark, updateName: user.nickName, updateUserName: user.userName },
      whereObj: { id },
      remark: `GatherParameter表更新采集信息`,
    });
    await this.operationLogService.add(
      {
        type: 'update',
        msg: `采集管理模块更新采集信息`,
        databaseOperationLogList,
        remark: `更新采集${data.parameterName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 删除
   */
  async delete(idList, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];

    await this.gatherParameterRepository.delete(idList);

    databaseOperationLogList.push({
      type: 'delete',
      dataType: 'array',
      database: 'GatherParameter',
      checkOnlyKeyList: [],
      data: null,
      whereObj: idList,
      remark: `GatherParameter表删除采集`,
    });
    await this.operationLogService.add(
      {
        type: 'delete',
        msg: `采集管理模块删除采集`,
        databaseOperationLogList,
        remark: `删除采集`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  async isExistKey(parameterCode: string) {
    const result = await this.gatherParameterRepository.findOne({ where: { parameterCode } });

    if (result) {
      throw new ApiException(10032);
    }
  }

  async isExistKey2(idList) {
    for (let i = 0; i < idList.length; i++) {
      const result2 = await this.gatherMachineParameterRepository.findOne({
        where: { parameterId: idList[i] },
      });

      if (result2) {
        throw new ApiException(10033);
      }
    }
  }
}
